package com.baizhi.config;

import com.baizhi.realm.AuthenRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 声明当前类为一个配置类
 */
@Configuration
public class ShiroConfig {
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        /**
         * anon 代表匿名可访问 就是不用登陆
         * authc 代表登陆后才能访问
         */
        Map map = new HashMap();
        map.put("/login.jsp","anon");
        map.put("/admin/*","anon");
        map.put("/main.jsp","authc");
        map.put("/guru","authc");
        map.put("/menu/*","authc");
        map.put("/jsp/*","authc");
        factoryBean.setFilterChainDefinitionMap(map);
        factoryBean.setSecurityManager(defaultWebSecurityManager);
        return factoryBean;
    }
    @Bean
    public DefaultWebSecurityManager securityManager(AuthenRealm authenRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(authenRealm);
        return securityManager;
    }

    /**
     * 自定义authenRealm类
     * @param hashedCredentialsMatcher
     * @return
     */
    @Bean
    public AuthenRealm authenRealm(HashedCredentialsMatcher hashedCredentialsMatcher){

        return new AuthenRealm();
    }
    /**
     * 密码校验规则 HashedCredentialsMatcher
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        hashedCredentialsMatcher.setHashIterations(1024);
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
        return hashedCredentialsMatcher;
    }
}
